package com.dmlll.controller;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmlll.VO.*;
import com.dmlll.common.DataGridView;
import com.dmlll.common.ResultObj;
import com.dmlll.config.ExcelRead;
import com.dmlll.config.ToExcel;
import com.dmlll.domain.DrugMessage;
import com.dmlll.domain.Provider;
import com.dmlll.domain.ProviderArea;
import com.dmlll.domain.ProviderDrugCatalogControl;
import com.dmlll.service.ProviderAreaService;
import com.dmlll.service.ProviderDrugCatalogControlService;
import com.dmlll.service.ProviderService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dmLll
 * @since 2021-04-02
 */
@RestController
@RequestMapping("/provider")
public class ProviderController {

    @Autowired
    private ProviderService providerService;
    @Autowired
    private ProviderDrugCatalogControlService providerDrugCatalogControlService;
    @Autowired
    private ProviderAreaService providerAreaService;


    @RequestMapping("/getAllAvaProvider")
    public DataGridView getAllAvaProvider(Integer drugMessageId, Integer areaid) {
        QueryWrapper<ProviderDrugCatalogControl> wrapper = new QueryWrapper<>();
        wrapper.eq("drug_message_id", drugMessageId);//查出含有该药的供应商
        //所有供应此药的供应商
        List<ProviderDrugCatalogControl> controls = providerDrugCatalogControlService.list(wrapper);
        List<Provider> providers = new ArrayList<>();
        for (ProviderDrugCatalogControl catalogControl : controls) {
            providers.add(providerService.getById(catalogControl.getProviderId()));
        }
        List<Provider> providerList = new ArrayList<>();
        for (Provider provider : providers) {
            ProviderArea providerArea = providerAreaService.getOne(new QueryWrapper<ProviderArea>()
                    .eq("aid", areaid)
                    .eq("pid", provider.getId())
            );
            if (providerArea != null) {
                providerList.add(provider);
            }
        }
        return new DataGridView(providerList);
    }


    @RequestMapping("loadAllProvider")
    public List<Provider> loadAllProvider() {
        return providerService.list();
    }

    @RequestMapping("loadProvider")
    public DataGridView loadProvider(ProviderVO providerVO) {
        QueryWrapper<Provider> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(providerVO.getProviderName()), "providerName", providerVO.getProviderName());
        IPage<Provider> page = providerService.page(new Page<>(providerVO.getPage(), providerVO.getLimit()), queryWrapper);
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    @RequestMapping("add")
    public ResultObj add(Provider provider, Integer pid) {
        try {
            providerService.save(provider);
            ProviderArea providerArea = new ProviderArea();
            providerArea.setAid(pid);
            providerArea.setPid(provider.getId());
            providerAreaService.save(providerArea);
        } catch (Exception e) {
            return ResultObj.ADD_ERROR;
        }
        return ResultObj.ADD_SUCCESS;
    }

    @RequestMapping("updateProvider")
    public ResultObj updateProvider(Provider provider) {
        try {
            providerService.updateById(provider);
        } catch (Exception e) {
            return ResultObj.UPDATE_ERROR;
        }
        return ResultObj.UPDATE_SUCCESS;
    }

    @RequestMapping("delete")
    public ResultObj delete(Provider provider) {
        try {
            QueryWrapper<ProviderDrugCatalogControl> wrapper = new QueryWrapper<>();
            wrapper.eq("provider_id", provider.getId());
            List<ProviderDrugCatalogControl> list = providerDrugCatalogControlService.list(wrapper);
            if (list.size() > 0) {
                return ResultObj.DELETE_HAVE_CATALOG;
            }
            providerService.removeById(provider.getId());
        } catch (Exception e) {
            return ResultObj.DELETE_ERROR;
        }
        return ResultObj.DELETE_SUCCESS;
    }

    //模糊分页查
    @RequestMapping("/findAll")
    @ResponseBody
    public PageInfo<DeliverGoodsVO> findAll(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                                            DeliverGoodDTO deliverGoodDTO,@RequestParam("id") Integer id) {
        PageInfo<DeliverGoodsVO> list = providerService.findAll(pageNum, pageSize, deliverGoodDTO,id);
        return list;
    }

    //导出
    @RequestMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response, Integer[] idList) {
        List<DeliverGoodsVO> list = new ArrayList<>();
        if (idList.length > 0) {
            list = providerService.findByIdList(idList);
        }
        List<List<String>> lists = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        for (int i = 0; i < list.size(); i++) {
            DeliverGoodsVO deliverGoodsVO = list.get(i);
            List<String> list1 = new ArrayList<>();
            list1.add(deliverGoodsVO.getPurchaseNum());
            list1.add(deliverGoodsVO.getProductionName());
            list1.add(deliverGoodsVO.getHospitalName());
            list1.add(format.format(deliverGoodsVO.getCreateTime()));
            list1.add(format.format(deliverGoodsVO.getRecentTime()));
            list1.add(deliverGoodsVO.getSerialNumber());
            list1.add(deliverGoodsVO.getCommonName());
            list1.add(deliverGoodsVO.getCommodityName());
            list1.add(deliverGoodsVO.getDosageForm());
            list1.add(deliverGoodsVO.getSize());
            list1.add(deliverGoodsVO.getUnit());
            list1.add(deliverGoodsVO.getFactor().toString());
            list1.add(deliverGoodsVO.getProductionName());
            list1.add(deliverGoodsVO.getWinPrice().toString());
            list1.add(deliverGoodsVO.getTrading().toString());
            list1.add(deliverGoodsVO.getPurchaseAmount().toString());
            String zongjiage = String.valueOf((deliverGoodsVO.getTrading() * deliverGoodsVO.getPurchaseAmount()));
            list1.add(zongjiage);
            list1.add(deliverGoodsVO.getProviderName());
            String zt = "";
            if (deliverGoodsVO.getPurchaseState() == 1) {
                zt = "未确认送货";
            } else if (deliverGoodsVO.getPurchaseState() == 2) {
                zt = "已发货";
            } else if (deliverGoodsVO.getPurchaseState() == 3) {
                zt = "已入库";
            } else if (deliverGoodsVO.getPurchaseState() == 4) {
                zt = "取消供货";
            } else {
                zt = "到期未供货";
            }
            list1.add(zt);
            lists.add(list1);
        }
        String[] heads = {"采购单编号", "采购单名称", "采购医院", "开始采购时间", "结束采购时间", "流水号", "通用名", "商品名", "剂型", "规格", "单位", "转换系数", "生产企业", "中标价", "交易价", "采购量", "采购总金额", "供货企业", "采购状态"};
        String filename = "供货商采购单";
        new ToExcel<DeliverGoodsVO>().excel(filename, heads, response, lists);
    }

    @RequestMapping("/moban")
    @ResponseBody
    public void moban(HttpServletResponse response) {
        List<List<String>> lists = new ArrayList<>();
        String[] heads = {"采购单编号", "采购单名称", "采购医院", "开始采购时间", "结束采购时间", "流水号", "通用名", "商品名", "剂型", "规格", "单位", "转换系数", "生产企业", "中标价", "交易价", "采购量", "采购总金额", "供货企业", "采购状态"};
        String filename = "供货商采购单模板";
        new ToExcel<DeliverGoodsVO>().excel(filename, heads, response, lists);
    }

    //发货
    @RequestMapping("/updata")
    @ResponseBody
    public String updataDeliverGoodsVO(@RequestParam("idList") Integer[] idList) {
        int i;
        i = providerService.deleteByinList(idList);
        return JSONUtil.toJsonStr("成功发货" + i + "条");
    }

    //无法供货
    @RequestMapping("/updatawu")
    @ResponseBody
    public String updata(@RequestParam("idList") Integer[] idList) {
        int i;
        i = providerService.deleteWuinList(idList);
        return JSONUtil.toJsonStr("取消发货" + i + "条");
    }

    //导入发货
    @RequestMapping("/excelRead")
    @ResponseBody
    public String excelRead(@RequestParam("file") MultipartFile multipartFile) {
        List<List<String>> lists = ExcelRead.readExcel(multipartFile);
        Integer[] idList = new Integer[lists.size() - 1];
        int tiao = 0;
        for (int i = 1; i < lists.size(); i++) {
            List<String> list = lists.get(i);
            DeliverGoodsVO deliverGoodsVO = new DeliverGoodsVO();
            deliverGoodsVO.setPurchaseNum(list.get(0));
            deliverGoodsVO.setHospitalName(list.get(2));
            deliverGoodsVO.setSerialNumber(list.get(5));
            idList[i - 1] = providerService.deletdaoru(deliverGoodsVO);
            tiao++;
        }
        providerService.deleteByinList(idList);
        return JSONUtil.toJsonStr("成功发货" + tiao + "条");
    }


    //商品管理信息查询
    @RequestMapping("/findguanli")
    @ResponseBody
    public PageInfo<DrugMessageVOgcl> findguanli(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                                 @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                                                 DrugMessageDTOgcl drugMessageDTOgcl,@RequestParam("id")Integer id) {
        PageInfo<DrugMessageVOgcl> list = providerService.findguanli(pageNum, pageSize, drugMessageDTOgcl,id);
        return list;

    }

    //取消供货
    @RequestMapping("/deleteGongidList")
    @ResponseBody
    public String deleteGongidList(Integer[] idList) {
        int i = providerService.deleteGongidList(idList);
        return JSONUtil.toJsonStr("取消供货" + i + "条");
    }

    //确认供货页面查询
    @RequestMapping("/findyao")
    @ResponseBody
    public PageInfo<DrugMessageVOgcl> findyao(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                              @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                                              DrugMessageDTOgcl drugMessageDTOgcl,@RequestParam("id")Integer id) {
        PageInfo<DrugMessageVOgcl> list = providerService.findyao(pageNum, pageSize, drugMessageDTOgcl,id);
        return list;

    }

    //确认供货
    @RequestMapping("/insert")
    @ResponseBody
    public String insert(@RequestParam("Sid") Integer Sid,
                         @RequestParam("idList") Integer[] idList
    ) {
        List<Integer[]> list = new ArrayList<>();

        for (int a = 0; a < idList.length; a++) {
            Integer[] list1 = new Integer[3];
            list1[0] = Sid;
            list1[1] = idList[a];
            list1[2] = 2;
            list.add(list1);
        }


        int i = providerService.insertQueren(list);
        return JSONUtil.toJsonStr("确认供货" + i + "条");
    }

    //供应商药品维护页面查询
    @RequestMapping("/maintain")
    @ResponseBody
    public PageInfo<Drug_maintenanceVOgcl> maintain(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                                                    DrugmaintenanceDTOgcl drugmaintenanceDTOgcl) {
        PageInfo<Drug_maintenanceVOgcl> list = providerService.findmaintain(pageNum, pageSize, drugmaintenanceDTOgcl);
        return list;
    }

    //供应商药品维护页面查询导出
    @RequestMapping("/maintainexcel")
    @ResponseBody
    public void maintainexcel(HttpServletResponse response) {
        List<Drug_maintenanceVOgcl> list = new ArrayList<>();
        list = providerService.findAllExcel();

        List<List<String>> lists = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Drug_maintenanceVOgcl drug_maintenanceVOgcl = list.get(i);
            List<String> list1 = new ArrayList<>();
            list1.add(drug_maintenanceVOgcl.getSerialNumber());
            list1.add(drug_maintenanceVOgcl.getCommonName());

            list1.add(drug_maintenanceVOgcl.getDosageForm());
            list1.add(drug_maintenanceVOgcl.getSize());
            list1.add(drug_maintenanceVOgcl.getUnit());
            list1.add(drug_maintenanceVOgcl.getFactor().toString());
            list1.add(drug_maintenanceVOgcl.getProductionName());
            list1.add(drug_maintenanceVOgcl.getCommodityName());
            list1.add(drug_maintenanceVOgcl.getWinPrice().toString());
            list1.add(drug_maintenanceVOgcl.getDataName());
            list1.add(drug_maintenanceVOgcl.getCategory());
            String zt = "";
            if (drug_maintenanceVOgcl.getTransaction() == 1) {
                zt = "正常";
            } else {
                zt = "暂停交易";
            }

            list1.add(zt);
            list1.add(drug_maintenanceVOgcl.getProviderName());
            String jdjg = "";
            if (drug_maintenanceVOgcl.getControlState() == 1) {
                jdjg = "审核通过";
            } else {
                jdjg = "审核未通过";
            }
            list1.add(jdjg);
            lists.add(list1);
        }
        String[] heads = {"流水号", "通用名", "剂型", "规格", "单位", "转换系数", "生产企业", "商品名", "中标价", "质量层次", "药品类别", "采购状态", "供货企业", "审核状态"};
        String filename = "商品信息";
        new ToExcel<Drug_maintenanceVOgcl>().excel(filename, heads, response, lists);
    }

    //供应商药品维护页面修改反显
    @RequestMapping("/weixiu")
    @ResponseBody
    public List<DrugMessage> weixiu(@RequestParam("id") Integer id) {
        return providerService.findAllxiu(id);
    }


    //查询所有供应商的名字
    @RequestMapping("/providerName")
    @ResponseBody
    public List<Provider> providerName() {

        return providerService.findgongName();
    }

    //修改
    @RequestMapping("/update")
    @ResponseBody
    public String update(@RequestParam(value = "JsonPojo") String JsonPojo) {
        DrugMessage drugMessage = JSON.parseObject(JsonPojo, DrugMessage.class);
        int a = providerService.updateXiugai(drugMessage);
        return JSONUtil.toJsonStr("修改成功" + a + "条");
    }

    //根据id查询药品的详细信息
    @RequestMapping("/particulargcl")
    @ResponseBody
    public List<ParticularVOgcl> particular(@RequestParam("id") Integer id) {
        return providerService.findXiangxi(id);
    }

    //供货商审核信息查询
    @RequestMapping("/SupplierAudit")
    @ResponseBody

    public PageInfo<Drug_maintenanceVOgcl> SupplierAudit(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                                         @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                                                         DrugmaintenanceDTOgcl drugmaintenanceDTOgcl) {
        return providerService.findGongshen(pageNum, pageSize, drugmaintenanceDTOgcl);
    }

    //确认供货
    @RequestMapping("/approve")
    @ResponseBody
    public String approve(@RequestParam("idList") Integer[] idList) {

        int i = providerService.insertGongtong(idList);
        return JSONUtil.toJsonStr("确认供货" + i + "条");
    }

    //药品品目维护查询
    @RequestMapping("/Items")
    @ResponseBody
    public PageInfo<DrugMessageVOgcl> Items(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "6") Integer pageSize,
                                            DrugMessageDTOgcl drugMessageDTOgcl) {
        return providerService.findweihuyao(pageNum, pageSize, drugMessageDTOgcl);
    }

    //修改药品品目
    @RequestMapping("/updateItems")
    @ResponseBody
    public String updateItems(@RequestParam(value = "JsonPojo") String JsonPojo) {
        DrugMessageVOgcl drugMessageVOgcl = JSON.parseObject(JsonPojo, DrugMessageVOgcl.class);
        int a = providerService.updateGuanxiu(drugMessageVOgcl);
        return JSONUtil.toJsonStr("修改成功" + a + "条");
    }

    //删除药品表数据
    @RequestMapping("/delectdrug")
    @ResponseBody
    public String delectdrug(@RequestParam("id") Integer id) {
        int i = providerService.deleteDrugidList(id);
        return JSONUtil.toJsonStr("成功删除" + i + "条");
    }

    //添加药品信息
    @RequestMapping("/insertdrug")
    @ResponseBody
    public String insertdrug(DrugMessage drugMessage) {
        int i = providerService.insettian(drugMessage);
        return JSONUtil.toJsonStr("成功添加" + i + "条信息");
    }

    //根据药品id导出药品信息
    @RequestMapping("/drugidList")
    @ResponseBody
    public void drugidList(HttpServletResponse response, Integer[] idList) {
        List<DrugMessageVOgcl> list = new ArrayList<>();
        if (idList.length > 0) {
            list = providerService.findBydrug(idList);
        }
        List<List<String>> lists = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            DrugMessageVOgcl drugMessageVOgcl=list.get(i);
            List<String> list1 = new ArrayList<>();
            list1.add(drugMessageVOgcl.getSerialNumber());
            list1.add(drugMessageVOgcl.getCommonName());
            list1.add(drugMessageVOgcl.getDosageForm());
            list1.add(drugMessageVOgcl.getSize());
            list1.add(drugMessageVOgcl.getUnit());
            list1.add(drugMessageVOgcl.getFactor().toString());
            list1.add(drugMessageVOgcl.getCategory());

            String zt = "";
            if (drugMessageVOgcl.getTransaction() == 1) {
                zt = "正常";
            } else {
                zt = "暂停交易";
            }
            list1.add(zt);
            lists.add(list1);
        }
        String[] heads = { "流水号", "通用名", "剂型", "规格", "单位", "转换系数","药品类别","药品交易状态"};
        String filename = "药品品目表";
        new ToExcel<DrugMessageVOgcl>().excel(filename, heads, response, lists);
    }
    //导入添加药品信息
    @RequestMapping("/exeldrug")
    @ResponseBody
    public String exeldrug(@RequestParam("file") MultipartFile multipartFile) {
        List<List<String>> lists=ExcelRead.readExcel(multipartFile);
        int tiao = 0;
        for (int i = 1; i < lists.size(); i++) {
            List<String> list = lists.get(i);
            DrugMessage drugMessage = new DrugMessage();
            drugMessage.setSerialNumber(list.get(0));
            drugMessage.setCommonName(list.get(1));
            drugMessage.setDosageForm(list.get(2));
            drugMessage.setSize(list.get(3));
            drugMessage.setUnit(list.get(4));
            drugMessage.setFactor(Integer.valueOf(list.get(5)));
            String category=list.get(6);
            Integer m = providerService.category(category);
            System.out.println("!!!!!!!!!!!!!!!"+m);

            drugMessage.setDrugCategory(m);
            int zt=0;
            if (list.get(7).equals("正常") || list.get(7)=="正常"){
                zt=1;
            }else{
                zt=2;
            }
            drugMessage.setTransaction(zt);
            tiao+=providerService.insettian(drugMessage);

        }
        return JSONUtil.toJsonStr("成功导入" + tiao + "条");
    }
    @RequestMapping("/drugmoban")
    @ResponseBody
    public void drugmoban(HttpServletResponse response) {
        List<List<String>> lists = new ArrayList<>();
        String[] heads = {"流水号", "通用名", "剂型", "规格", "单位", "转换系数","药品类别","药品交易状态"};
        String filename = "药品品目模板";
        new ToExcel<DeliverGoodsVO>().excel(filename, heads, response, lists);
    }


    @RequestMapping("/getProvider")
    public List<Provider> getProvider(){
        List<Provider> list = providerService.list();
        return list;
    }
    @RequestMapping("/getProviderById")
    public Provider getProviderById(Integer id){
        return providerService.getById(id);
    }



}

